#include "common.h"
#include "memory/tlb.h"
#include <time.h>
#include <stdlib.h>

void init_tlb() {
    int i;
    for (i = 0; i < TLB_SIZE; i ++) {
        tlb[i].valid_bit = false;
    }
}

int tlb_read(lnaddr_t addr) {
    uint32_t tag = addr >> 12;
    int i;
    for (i = 0; i < TLB_SIZE; i ++) {
        if (tlb[i].valid_bit && tlb[i].tag == tag) {
            return i;
        }
    }
    return -1;
}

void tlb_write(lnaddr_t addr, hwaddr_t hwaddr) {
    uint32_t tag = addr >> 12;
    int i;
    for (i = 0; i < TLB_SIZE; i ++) {
        if (!tlb[i].valid_bit) {
            tlb[i].valid_bit = true;
            tlb[i].tag = tag;
            tlb[i].page_info = hwaddr >> 12;
            return;
        }
    }
    srand(time(0));
    i = rand() % TLB_SIZE;
    tlb[i].tag = tag;
    tlb[i].page_info = hwaddr >> 12;
}